Telegram Group & Telegram Channel
🔰 How to: как сделать логические выражения в Python читаемыми

Длинные логические выражения — бич читаемости. Вот простой пример:
if user["verified"] and event["date"] > datetime.now() and not event["full"]:
print("Here's the event signup form...")


Выглядит компактно, но читается не очень. Есть несколько способов сделать лучше.

📝 Разбивка по строкам с операторами в начале
if (user["verified"]
and event["date"] > datetime.now()
and not event["full"]):
print("Here's the event signup form...")


PEP8 рекомендует именно такой стиль — с операторами (and, or) в начале строки.

📝 Использование переменных для подвыражений
user_is_verified = user["verified"]
event_in_future = event["date"] > datetime.now()
event_not_full = not event["full"]

if user_is_verified and event_in_future and event_not_full:
print("Here's the event signup form...")


Такой подход улучшает понимание выражения до того, как вы вчитываетесь в детали.

📝 Использование функций вместо переменных
def is_verified(user): return user["verified"]
def in_future(event): return event["date"] > datetime.now()
def not_full(event): return not event["full"]

if is_verified(user) and in_future(event) and not_full(event):
print("Here's the event signup form...")


Функции полезны, если важно сохранить short-circuit поведение (когда выражения дальше не выполняются, если результат уже ясен).

📝 Закон де Моргана для упрощения условий

Если видите выражение вида not (a or b) — можно применить трансформацию:
# Было:
not (a or b)

# Стало:
not a and not b


Пример:
def can_only_read(user):
return not (
user["role"] == "admin"
or "edit" in user["permissions"]
)


Упростим по де Моргану:
def can_only_read(user):
return user["role"] != "admin" and "edit" not in user["permissions"]


Теперь читается проще и интуитивнее.

Вывод: не бойтесь разбивать выражения, давать им имена и упрощать через логические законы. Код должен быть понятным не только компьютеру, но и людям.

Библиотека питониста #буст
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/pyproglib/6693
Create:
Last Update:

🔰 How to: как сделать логические выражения в Python читаемыми

Длинные логические выражения — бич читаемости. Вот простой пример:

if user["verified"] and event["date"] > datetime.now() and not event["full"]:
print("Here's the event signup form...")


Выглядит компактно, но читается не очень. Есть несколько способов сделать лучше.

📝 Разбивка по строкам с операторами в начале
if (user["verified"]
and event["date"] > datetime.now()
and not event["full"]):
print("Here's the event signup form...")


PEP8 рекомендует именно такой стиль — с операторами (and, or) в начале строки.

📝 Использование переменных для подвыражений
user_is_verified = user["verified"]
event_in_future = event["date"] > datetime.now()
event_not_full = not event["full"]

if user_is_verified and event_in_future and event_not_full:
print("Here's the event signup form...")


Такой подход улучшает понимание выражения до того, как вы вчитываетесь в детали.

📝 Использование функций вместо переменных
def is_verified(user): return user["verified"]
def in_future(event): return event["date"] > datetime.now()
def not_full(event): return not event["full"]

if is_verified(user) and in_future(event) and not_full(event):
print("Here's the event signup form...")


Функции полезны, если важно сохранить short-circuit поведение (когда выражения дальше не выполняются, если результат уже ясен).

📝 Закон де Моргана для упрощения условий

Если видите выражение вида not (a or b) — можно применить трансформацию:
# Было:
not (a or b)

# Стало:
not a and not b


Пример:
def can_only_read(user):
return not (
user["role"] == "admin"
or "edit" in user["permissions"]
)


Упростим по де Моргану:
def can_only_read(user):
return user["role"] != "admin" and "edit" not in user["permissions"]


Теперь читается проще и интуитивнее.

Вывод: не бойтесь разбивать выражения, давать им имена и упрощать через логические законы. Код должен быть понятным не только компьютеру, но и людям.

Библиотека питониста #буст

BY Библиотека питониста | Python, Django, Flask




Share with your friend now:
tg-me.com/pyproglib/6693

View MORE
Open in Telegram


Библиотека питониста | Python Django Flask Telegram | DID YOU KNOW?

Date: |

The Singapore stock market has alternated between positive and negative finishes through the last five trading days since the end of the two-day winning streak in which it had added more than a dozen points or 0.4 percent. The Straits Times Index now sits just above the 3,060-point plateau and it's likely to see a narrow trading range on Monday.

Pinterest (PINS) Stock Sinks As Market Gains

Pinterest (PINS) closed at $71.75 in the latest trading session, marking a -0.18% move from the prior day. This change lagged the S&P 500's daily gain of 0.1%. Meanwhile, the Dow gained 0.9%, and the Nasdaq, a tech-heavy index, lost 0.59%. Heading into today, shares of the digital pinboard and shopping tool company had lost 17.41% over the past month, lagging the Computer and Technology sector's loss of 5.38% and the S&P 500's gain of 0.71% in that time. Investors will be hoping for strength from PINS as it approaches its next earnings release. The company is expected to report EPS of $0.07, up 170% from the prior-year quarter. Our most recent consensus estimate is calling for quarterly revenue of $467.87 million, up 72.05% from the year-ago period.

Библиотека питониста | Python Django Flask from tr


Telegram Библиотека питониста | Python, Django, Flask
FROM USA